package com.originskyseed.platform.user.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.tenant.util.TenantCodeUtil;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.user.mapper.DeptMapper;
import com.originskyseed.platform.user.mapper.UserInfoMapper;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IDeptService;

/**
 * 部门表Service接口实现类（OSI_DEPT）
 *
 * @author Tangwanghui
 */
@DubboService
@Component("deptService")
public class DeptServiceImpl implements IDeptService {

	@Resource
	private DeptMapper deptMapper;

	@Resource
	private UserInfoMapper userInfoMapper;

	/**
	 * 删除记录
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public int deleteByPrimaryKey(String id) throws Exception {
		return this.deptMapper.deleteByPrimaryKey(id);
	}

	/**
	 * 批量删除记录
	 *
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@Override
	public int deleteByPrimaryKeys(List<String> ids) throws Exception {
		return this.deptMapper.deleteByPrimaryKeys(ids);
	}

	/**
	 * 批量删除记录
	 *
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateIsDel(List<String> ids) throws Exception {
		return this.deptMapper.updateIsDel(ids);
	}

	/**
	 * 插入记录
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insert(Dept record) throws Exception {
		if (StringUtils.isBlank(record.getId())) {
			record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
		}
		record.setCreateTime(new Date());
		return this.deptMapper.insert(record);
	}

	/**
	 * 插入记录（仅非空值字段）
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insertSelective(Dept record) throws Exception {
		if (StringUtils.isBlank(record.getId())) {
			record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
		}
		record.setCreateTime(new Date());
		return this.deptMapper.insertSelective(record);
	}

	/**
	 * 更新记录
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByPrimaryKey(Dept record) throws Exception {
		record.setUpdateTime(new Date());
		return this.deptMapper.updateByPrimaryKey(record);
	}

	/**
	 * 更新记录（仅非空值字段）
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByPrimaryKeySelective(Dept record) throws Exception {
		record.setUpdateTime(new Date());
		return this.deptMapper.updateByPrimaryKeySelective(record);
	}

	/**
	 * 置顶接口
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	public int updateIsTop(Dept record) throws Exception {

		this.deptMapper.updateIsTop();

		record.setUpdateTime(new Date());
		return this.deptMapper.updateByPrimaryKeySelective(record);
	}

	/**
	 * 查询记录
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public Dept selectByPrimaryKey(String id) throws Exception {
		return this.deptMapper.selectByPrimaryKey(id);
	}

	@Override
	public Dept selectByPrimaryKeyTenantCode(String id, String tenantCode) throws Exception {
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		return this.selectByPrimaryKey(id);
	}

	/**
	 * 查询列表
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Dept> selectList(Dept record) throws Exception {
		return this.deptMapper.selectList(record);
	}

	/**
	 * 分页查询列表
	 *
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<Dept> selectListByPage(Map<String, Object> params, BasePage<Dept> page) throws Exception {
		params.put("page", page);
		List<Dept> list = this.deptMapper.selectListByPage(params);
		page.setResults(list);
		return page;
	}

	/**
	 * 批量更改部门状态
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateStatusByIds(Map<String, Object> params) throws Exception {
		return this.deptMapper.updateStatusByIds(params);
	}

	@Override
	public JSONArray selectDeptTreeList() throws Exception {
		// 获取所有部门列表
		Dept deptQuery = new Dept();
		deptQuery.setIsDel(0);
		List<Dept> deptList = this.deptMapper.selectList(deptQuery);
		List<Dept> parentList = new ArrayList<Dept>();
		for (Dept dept : deptList) {
			if (StringUtils.isBlank(dept.getParentCode())) {
				parentList.add(dept);
			}
		}
		// 递归构建
		return build2Tree(deptList, parentList);
	}

	@Override
	public JSONArray selectDeptTreeList(Integer sourceSys) throws Exception {
		// 获取所有部门列表
		Dept deptQuery = new Dept();
		deptQuery.setIsDel(0);
		deptQuery.setSourceSys(sourceSys);
		List<Dept> deptList = this.deptMapper.selectList(deptQuery);
		List<Dept> parentList = new ArrayList<Dept>();
		for (Dept dept : deptList) {
			if ("00000001".equals(dept.getParentCode())) {
				parentList.add(dept);
			}
		}
		// 递归构建
		return build2Tree(deptList, parentList);
	}

	@Override
	public void selectUserDeptTreeList(Dept dept, JSONObject jsonObject,Integer type) throws Exception {
		List<Dept> deptList = this.deptMapper.selectByParentCode(dept.getCode());
		if (deptList != null && deptList.size() > 0) {
			JSONArray jsonArray = new JSONArray();
			if(jsonObject.containsKey("children")){
				jsonArray = (JSONArray)jsonObject.get("children");
			}
			JSONObject obj;
			for (Dept sonDept : deptList) {
				//int userNum = this.userInfoMapper.selectUserNumByStatusDeptId(sonDept.getId());
				obj = new JSONObject();
				obj.put("id", sonDept.getId());
				obj.put("code", sonDept.getCode());
				obj.put("parentCode", sonDept.getParentCode());
				obj.put("name", sonDept.getName());
				obj.put("sourceSys", sonDept.getSourceSys());
				obj.put("type", sonDept.getType());
				//obj.put("userNum",userNum);

				// 查询业务员
				if(type==0 && sonDept.getSourceSys()==2){
					UserInfo query = new UserInfo();
					query.setDeptId(sonDept.getId());
					query.setType(6);
					List<UserInfo> userInfoList = this.userInfoMapper.selectList(query);
					JSONArray array = new JSONArray();
					for (UserInfo userInfo : userInfoList) {
						JSONObject jsonObject1 = new JSONObject();
						jsonObject1.put("id", userInfo.getId());
						jsonObject1.put("code", userInfo.getId());
						jsonObject1.put("parentCode", sonDept.getCode());
						jsonObject1.put("name", userInfo.getName());
						jsonObject1.put("sourceSys", sonDept.getSourceSys());
						jsonObject1.put("type", 6);
						array.add(jsonObject1);
					}
					obj.put("children", array);
					// 查询主播
				}else if(type == 0 && sonDept.getSourceSys()==1){
					UserInfo query = new UserInfo();
					query.setDeptId(sonDept.getId());
					query.setType(11);
					List<UserInfo> userInfoList = this.userInfoMapper.selectList(query);
					JSONArray array = new JSONArray();
					for (UserInfo userInfo : userInfoList) {
						JSONObject jsonObject1 = new JSONObject();
						jsonObject1.put("id", userInfo.getId());
						jsonObject1.put("code", userInfo.getId());
						jsonObject1.put("parentCode", sonDept.getCode());
						jsonObject1.put("name", userInfo.getName());
						jsonObject1.put("sourceSys", sonDept.getSourceSys());
						jsonObject1.put("type", 4);
						array.add(jsonObject1);
					}
					obj.put("children", array);
				}
				if(!sonDept.getCode().equals(sonDept.getParentCode())){
					selectUserDeptTreeList(sonDept, obj,type);
				}
				jsonArray.add(obj);
			}
			jsonObject.put("children", jsonArray);
		}
	}

	/**
	 * 查询部门编号
	 *
	 * @return
	 * @throws Exception
	 */
	public String selectDeptCode() throws Exception {
		return this.deptMapper.selectDeptCode();
	}

	/**
	 * 根据code查询
	 *
	 * @param code
	 * @return
	 * @throws Exception
	 */
	@Override
	public Dept selectByCode(String code) throws Exception {
		return this.deptMapper.selectByCode(code);
	}

	@Override
	public Dept selectByCodeTenantCode(String code, String tenantCode) throws Exception {
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		return this.selectByCode(code);
	}

	/**
	 * 查询最大的优先级
	 *
	 * @return
	 * @throws Exception
	 */
	public Integer selectPrority() throws Exception {
		return this.deptMapper.selectPriority();
	}

	/**
	 * 根据优先级查询部门
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public Dept selectDeptByProritySort(Map<String, Object> map) throws Exception {
		return this.deptMapper.selectDeptByPrioritySort(map);
	}

	/**
	 * 根据优先级查询员工
	 *
	 * @param priority
	 * @return
	 * @throws Exception
	 */
	public Dept selectDeptByPrority(Integer priority) throws Exception {
		return this.deptMapper.selectDeptByPriority(priority);
	}

	/**
	 * 更新排序信息
	 *
	 * @param downDept
	 * @param upDept
	 * @return
	 * @throws Exception
	 */
	public int updatePrority(Dept downDept, Dept upDept) throws Exception {
		downDept.setUpdateTime(new Date());
		upDept.setUpdateTime(new Date());
		this.deptMapper.updateByPrimaryKeySelective(downDept);
		return this.deptMapper.updateByPrimaryKeySelective(upDept);
	}

	/**
	 * 根据父级code查询
	 *
	 * @param parentCode
	 * @return
	 * @throws Exception
	 */
	public List<Dept> selectByParentCode(String parentCode) throws Exception {
		return this.deptMapper.selectByParentCode(parentCode);
	}

	/**
	 * 查询是否有子级
	 *
	 * @param code
	 * @return
	 * @throws Exception
	 */
	public boolean selectIsHaveChildren(String id,String code) throws Exception {
		Integer userNum = this.userInfoMapper.selectIsHaveChildren(id);
		Integer deptNum = this.deptMapper.selectIsHaveChildren(code);
		return (userNum!=null&&userNum>0 )|| (deptNum!=null&&deptNum>0)   ? true:false;
	}

	@Override
	public List<Dept> selectByParentCodeTenantCode(String parentCode, String tenantCode) throws Exception {
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		return this.selectByParentCode(parentCode);
	}

	/**
	 * 查询是否存在子部门
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public boolean selectExistSon(String id) throws Exception {
		return this.deptMapper.selectExistSon(id);
	}

	/**
	 * 分页查询列表
	 *
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<Dept> selectListRelComByPage(Map<String, Object> params, BasePage<Dept> page) throws Exception {
		params.put("page", page);
		List<Dept> list = this.deptMapper.selectListRelComByPage(params);
		page.setResults(list);
		return page;
	}

	/**
	 * 查询分公司列表 和体系
	 *
	 * @return
	 * @throws Exception
	 */
	public List<Map<String, Object>> selectComposeList(Map<String, String> map) throws Exception {
		return this.deptMapper.selectComposeList(map);
	}

	/**
	 * 根据父级code和名称查询查询
	 *
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	public BasePage<Dept> selectByParentCodeAndName(Map<String, Object> params, BasePage<Dept> page) throws Exception {
		params.put("page", page);
		List<Dept> list = this.deptMapper.selectByParentCodeAndName(params);
		page.setResults(list);
		return page;
	}

	public List<String> selectGroupId(String id) throws Exception {
		List<String> list = new ArrayList<>();

		return list;
	}

	/**
	 * 构建树
	 *
	 * @param list       包含所有数据
	 * @param parentList 只包含根节点或父节点数据
	 * @return
	 */
	private JSONArray build2Tree(List<Dept> list, List<Dept> parentList) {
		JSONArray ary = new JSONArray();
		if (!list.isEmpty() && !parentList.isEmpty()) {
			JSONObject obj;
			// 移除父节点
			list.removeAll(parentList);
			List<Dept> childList;
			for (Dept dept : parentList) {
				obj = new JSONObject();
				obj.put("id", dept.getId());
				obj.put("code", dept.getCode());
				obj.put("parentCode", dept.getParentCode());
				obj.put("name", dept.getName());
				// 查找子节点
				childList = findChildren(list, dept);
				if (hasChildren(childList)) {
					obj.put("children", build2Tree(list, childList));
				}
				ary.add(obj);
			}
		}
		return ary;
	}

	/**
	 * 查找当前父节点下的子节点数据
	 *
	 * @param list       去除父节点的所有数据
	 * @param parentDept 父节点
	 * @return
	 */
	private List<Dept> findChildren(List<Dept> list, Dept parentDept) {
		List<Dept> childList = new ArrayList<Dept>();
		if (!list.isEmpty()) {
			for (Dept dept : list) {
				if (dept.getParentCode().equals(parentDept.getCode())) {
					childList.add(dept);
				}
			}
		}
		return childList;
	}

	private boolean hasChildren(List<Dept> list) {
		return list.size() > 0 ? true : false;
	}
}
